// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  Statistic,
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
  notification,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './All.less';

// 图片
const { Countdown } = Statistic;
/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ fu, loading }) => ({
  fu,
  loading: loading.models.fuRule,
}))
@Form.create()
class WaitSale extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    waitBuyAdd: '', // 表头处理结果
    deadline: Date.now() + 1000 * 6, // 倒计时
    currentDataSource: [],
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const {
      fu: { stocksFilters },
    } = this.props;
    return [
      {
        title: 'ID',
        width: window.outerWidth < 400 ? 40 : 300,
        dataIndex: 'id',
      },
      {
        title: '股票代码',
        dataIndex: 'stock',
        width: window.outerWidth < 400 ? 85 : 300,
        sorter: (a, b) => {
          const c = [a.stock, b.stock].sort();
          if (c[0] === a.stock) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
      },
      {
        title: '涨跌幅',
        dataIndex: 'gain',
        width: window.outerWidth < 400 ? 70 : 300,

        sorter: (a, b) => a.gain - b.gain,
        render: (value, row, index) => {
          return (
            <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
              {typeof value === 'number' || typeof value === 'string'
                ? `${value.toFixed(2).toString()}%`
                : null}
            </span>
          );
        },
        onCell: record => ({}),
      },
      {
        title: '涨跌幅/BETA',
        dataIndex: 'gainbeta',
        width: window.outerWidth < 400 ? 70 : 300,

        sorter: (a, b) => a.gainbeta - b.gainbeta,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toFixed(2).toString())
                : null}
            </span>
          );
        },
      },
      /* {
        title: 'ATR',
        dataIndex: 'atr',
        sorter: (a, b) => a.atr - b.atr,
        render: (value, row, index) => {
          return <span>{typeof value === 'number' || typeof value === 'string' ? NumberDivide(value.toFixed(2).toString()) : null}</span>;
        },
      }, */ {
        title: '操作',
        align: 'right',
        width: window.outerWidth < 400 ? 70 : 300,

        key: 'operation',
        render: (value, row, index) => <a onClick={this.delteWaitBuy.bind(this, value)}>删除</a>,
      },
    ];
  }

  changeWaitBuy(e) {
    this.setState({
      waitBuyAdd: e.target.value,
    });
  }

  addWaitBuy() {
    const { dispatch } = this.props;
    dispatch({
      type: 'fu/AddWaitBuy',
      payload: {
        state: 0,
        stock: this.state.waitBuyAdd,
      },
      callback: res => {
        dispatch({
          type: 'fu/GetWaitSale',
          payload: 0,
          callback: res => {
            this.setState({
              currentDataSource: res.list.waitBuyList,
            });
          },
        });
      },
    });
  }

  delteWaitBuy(record) {
    const { dispatch } = this.props;
    dispatch({
      type: 'fu/DeleteWaitBuy',
      payload: record.id,
      callback: res => {
        dispatch({
          type: 'fu/GetWaitSale',
          payload: 0,
          callback: res => {
            this.setState({
              currentDataSource: res.list.waitBuyList,
            });
          },
        });
      },
    });
  }

  /**
   *  Describe:倒计时
   *  Created by xjc on 2019/7/3
   */

  onFinish(a) {
    const { dispatch } = this.props;
    if (a === 1) {
      /* 导入列表数据 */
      dispatch({
        type: 'fu/GetWaitSale',
        payload: 0,
        callback: res => {
          message.success('刷新成功');
          this.setState({
            currentDataSource: res.list.waitBuyList,
            deadline: Date.now() + 1000 * 6, // 倒计时
          });
        },
      });
    } else {
      /* 导入列表数据 */
      dispatch({
        type: 'fu/GetWaitSale',
        payload: 0,
        callback: res => {
          this.setState({
            currentDataSource: res.list.waitBuyList,
            deadline: Date.now() + 1000 * 6, // 倒计时
          });
        },
      });
    }
  }

  clearAll() {
    const that = this;
    const key = `open${Date.now()}`;
    const { dispatch } = that.props;
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          notification.close(key);
          dispatch({
            type: 'fu/DeleteAllWaitBuy',
            payload: 0,
            callback: res => {
              dispatch({
                type: 'fu/GetWaitSale',
                payload: 0,
                callback: res => {
                  this.setState({
                    currentDataSource: res.list.waitBuyList,
                    deadline: Date.now() + 1000 * 6, // 倒计时
                  });
                },
              });
            },
          });
        }}
      >
        确定
      </Button>
    );
    notification.open({
      message: 'Notification Title',
      description: '是否全部删除',
      btn,
      key,
      onClose: close,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
  };

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      fu: { waitsale },
    } = this.props;
    const { listLoading, selectedRows, deadline } = this.state;
    let columns = [];
    if (columns.length === 0 && waitsale.code === 1) {
      columns = this.getColumns();
    }
    return (
      <PageHeaderWrapper title="待卖出股票">
        <Card>
          <Row>
            <Col md={16} sm={24}>
              <Input
                placeholder="若要传多个请用,间隔"
                style={{ width: '60%', margin: 12 }}
                // formatter={value => {return `${value}`.replace(/^[0-9a-zA-Z]*$/gi, '')}}
                onChange={this.changeWaitBuy.bind(this)}
              />
              <Button type="primary" onClick={this.addWaitBuy.bind(this)}>
                添加
              </Button>
              <Button style={{ marginLeft: 12 }} onClick={this.onFinish.bind(this, 1)}>
                刷新
              </Button>
              <Button style={{ marginLeft: 12 }} onClick={this.clearAll.bind(this, 1)}>
                清空
              </Button>
            </Col>
            <Col md={8} sm={24}>
              <span>
                <Countdown
                  title="剩余刷新时间："
                  value={deadline}
                  style={{ marginLeft: 15, fontSize: '1rem' }}
                  onFinish={this.onFinish.bind(this, 0)}
                  format=" s 秒"
                />
              </span>
            </Col>
          </Row>
          {waitsale.code === 0 ? (
            <Loading time={2000} />
          ) : (
            <div>
              <div>
                <span style={{ fontSize: '1rem', marginLeft: 15 }}>标普500涨跌幅： </span>
                <span
                  style={{
                    fontSize: '1.1rem',
                    color: waitsale.inx.gain > 0 ? '#389e0d' : '#e1111e',
                  }}
                >
                  {`${waitsale.inx.gain.toFixed(2)}%`}
                </span>
              </div>
              <div>
                <div style={{ margin: 15, fontSize: '1rem' }}>
                  共计：{this.state.currentDataSource.length}
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={listLoading}
                  data={waitsale}
                  columns={columns}
                  style={{ tableLayout: 'fixed' }}
                  className={styles.TableLayoutNo}
                  pagination={false}
                  // onChange={this.handleStandardTableChange}
                  scroll={{ x: window.outerWidth < 400 ? 375 : 1200, y: 618 }}
                />
              </div>
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'fu/GetWaitSale',
      payload: 0,
      callback: res => {
        this.setState({
          currentDataSource: res.list.waitBuyList,
        });
      },
    });
  }

  componentWillUnmount() {}
}

export default WaitSale;
